/* Copyright (c) 2009 Lintorus@EU-Destromath
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package authenticator;

import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

public class CodeCalculator {
  
  private long m_timeDifference;
  private HMac m_hMac;
  

  public CodeCalculator(byte[] a_secureKey, long a_timeDifference) {
    m_hMac = new HMac(new SHA1Digest());
    m_hMac.init(new KeyParameter(a_secureKey));
    m_timeDifference = a_timeDifference;
  }
  

  public String calculateCurrentCode(long a_currentLocalTime) {
    int currentCode = calculateCurrentCodeAsInt((a_currentLocalTime + m_timeDifference) / 30000L);
    String result = Integer.toString(currentCode);
    while (result.length() < 8) {
      result = "0" + result;
    }
    return result;
  }
  

  private int calculateCurrentCodeAsInt(long a_codeNumber) {
    m_hMac.update(Util.longToByteArray(a_codeNumber), 0, 8);
    byte[] macResult = new byte[m_hMac.getMacSize()];
    m_hMac.doFinal(macResult, 0);
    return selectIntFromMacResult(macResult) % 100000000;
  }
  
  
  public static String calculateCurrentCode(byte[] secretKey,
        long timeDifference) {
    CodeCalculator codeCalculator = new CodeCalculator(
	secretKey, timeDifference);
    long currentLocalTime = System.currentTimeMillis();
    String currentCode = codeCalculator
	.calculateCurrentCode(currentLocalTime);
    return currentCode;
}


private static int selectIntFromMacResult(byte[] a_macResult) {
    int position = a_macResult[a_macResult.length - 1] & 0x0F;
    return Util.byteArrayToInt(a_macResult, position) & 0x7FFFFFFF;
  }
    
}
